package com.example.game_app.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.game_app.R;
import com.example.game_app.adapter.GameListAdapter;
import com.example.game_app.util.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GameListViewFragment extends Fragment {
    // 游戏列表视图
    ListView listView;
    // 游戏元素集合
    List<Map<String, String>> gameList = new ArrayList<>();
    EditText searchEditText;
    Button searchButton;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件并返回视图
        return inflater.inflate(R.layout.game_list_view, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        listView = view.findViewById(R.id.gameLists);
        getGameList(view);
        // 监听 搜索按钮点击
        searchButton = view.findViewById(R.id.gameListSearchButton);
        searchEditText = view.findViewById(R.id.gameListSearchParam);
        // 根据搜索框内容模糊查询游戏列表
        searchButton.setOnClickListener(v -> {
            String searchParamStr = searchEditText.getText().toString();
            new Thread() {
                public void run() {
                    String result = Request.post("/games/search", "param=" + searchParamStr);
                    getJsonArray(result, gameList);
                }
            }.start();
        });
    }

    // 获取游戏列表并打印
    public void getGameList(View view) {
        new Thread() {
            @Override
            public void run() {
                Request request = new Request();
                String result = request.get("/games/list");
                // 将data数据转化为json数据
                getJsonArray(result, gameList);
            }
        }.start();
    }

    // 将data数据转化为json数据，并映射到ListView上
    public void getJsonArray(String data, List<Map<String, String>> gameList) {
        if (data == null || data.isEmpty()) {
            mHandler.post(new Runnable() {
                List<Map<String, String>> nullList = new ArrayList<>();
                @Override
                public void run() {
                    listView.setAdapter(new GameListAdapter(requireContext(), nullList));
                }
            });
        } else {
            try {

                JSONArray jsonArray = new JSONArray(data);
                // 保证每次访问后，列表情况，刷新数据
                gameList.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String gameId = String.valueOf(jsonObject.getInt("gameId"));
                    String gameName = jsonObject.getString("gameName");
                    String gameDescription = jsonObject.getString("gameDescription");
                    String gameImage = jsonObject.getString("gameImage");
                    Map<String, String> gameMap = new HashMap<>();
                    gameMap.put("gameId", gameId);
                    gameMap.put("gameName", gameName);
                    gameMap.put("gameDescription", gameDescription);
                    gameMap.put("gameImage", gameImage);
                    gameList.add(gameMap);
                }
                // 将数据映射到游戏列表
                mHandler.post(() -> listView.setAdapter(new GameListAdapter(requireContext(), gameList)));
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        }


    }

}
